using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;

namespace Lzfy_Refund_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class RefundTaskMasterController : ControllerBase
    {
        private readonly IRefundTaskMasterService _service;
        private readonly ILogger<RefundTaskMasterController> _logger;

        public RefundTaskMasterController(
            IRefundTaskMasterService service,
            ILogger<RefundTaskMasterController> logger)
        {
            _service = service;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有退费任务主表记录
        /// </summary>
        [HttpPost("get-all")]
        public async Task<ActionResult<IEnumerable<RefundTaskMasterResponse>>> GetAll()
        {
            try
            {
                var result = await _service.GetAllAsync();
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting all refund task masters");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据ID获取退费任务主表记录
        /// </summary>
        [HttpPost("get-by-id")]
        public async Task<ActionResult<RefundTaskMasterResponse>> GetById([FromBody] IdRequest request)
        {
            try
            {
                var result = await _service.GetByIdAsync(request.Id);
                if (result == null)
                {
                    return NotFound($"RefundTaskMaster with id {request.Id} not found");
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting refund task master by id: {Id}", request.Id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据用户名获取退费任务主表记录
        /// </summary>
        [HttpPost("get-by-username")]
        public async Task<ActionResult<IEnumerable<RefundTaskMasterResponse>>> GetByUsername([FromBody] UsernameRequest request)
        {
            try
            {
                var result = await _service.GetByUsernameAsync(request.Username);
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting refund task masters by username: {Username}", request.Username);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 根据条件查询退费任务主表记录（分页）
        /// </summary>
        [HttpPost("get-with-filter")]
        public async Task<ActionResult<object>> GetWithFilter([FromBody] RefundTaskMasterQueryRequest request)
        {
            try
            {
                var (data, totalCount) = await _service.GetWithFilterAsync(request);
                return Ok(new
                {
                    data,
                    totalCount,
                    pageIndex = request.PageIndex,
                    pageSize = request.PageSize,
                    totalPages = (int)Math.Ceiling((double)totalCount / request.PageSize)
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting refund task masters with filter");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 获取退费任务主表记录及其详情
        /// </summary>
        [HttpPost("get-with-details")]
        public async Task<ActionResult<RefundTaskMasterResponse>> GetWithDetails([FromBody] IdRequest request)
        {
            try
            {
                var result = await _service.GetWithDetailsAsync(request.Id);
                if (result == null)
                {
                    return NotFound($"RefundTaskMaster with id {request.Id} not found");
                }
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting refund task master with details by id: {Id}", request.Id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 创建退费任务主表记录
        /// </summary>
        [HttpPost("create")]
        public async Task<ActionResult<object>> Create([FromBody] RefundTaskMasterCreateRequest request)
        {
            try
            {
                var id = await _service.CreateAsync(request);
                return Ok(new { id });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating refund task master");
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 更新退费任务主表记录
        /// </summary>
        [HttpPost("update")]
        public async Task<ActionResult> Update([FromBody] RefundTaskMasterUpdateRequest request)
        {
            try
            {
                var success = await _service.UpdateAsync(request.Id, request);
                if (!success)
                {
                    return NotFound($"RefundTaskMaster with id {request.Id} not found");
                }
                return Ok(new { message = "更新成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error updating refund task master: {Id}", request.Id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 删除退费任务主表记录（同时删除关联的详情记录）
        /// </summary>
        [HttpPost("delete")]
        public async Task<ActionResult> Delete([FromBody] IdRequest request)
        {
            try
            {
                var success = await _service.DeleteAsync(request.Id);
                if (!success)
                {
                    return NotFound($"RefundTaskMaster with id {request.Id} not found");
                }
                return Ok(new { message = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error deleting refund task master: {Id}", request.Id);
                return StatusCode(500, "Internal server error");
            }
        }

        /// <summary>
        /// 创建退费任务主表记录并从HIS数据库批量导入明细数据
        /// </summary>
        [HttpPost("create-with-his-data")]
        public async Task<ActionResult<object>> CreateWithHisData([FromBody] RefundTaskMasterCreateRequest request)
        {
            try
            {
                var id = await _service.CreateWithHisDataAsync(request);
                return Ok(new { id, message = "创建成功并已导入HIS数据" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error creating refund task master with HIS data");
                return StatusCode(500, "Internal server error");
            }
        }
    }
}